package com.yutian.selfservice.support.utils;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.github.pagehelper.PageHelper;
import lombok.Data;

import javax.persistence.Transient;

@Data
public class PageSupport {
    @Transient
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    protected String isAsc;
    @Transient
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    protected String orderByColumn;
    @Transient
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    protected Integer pageNum;
    @Transient
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    protected Integer pageSize;

    private static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    private static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    private static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String SORT = "isAsc";


    /**
     * requestBody传递分页参数
     * @param pageSupport
     * @param
     */
    public static void startPage(PageSupport pageSupport) {
        if (pageSupport.getPageNum() != null && pageSupport.getPageSize() != null) {
            PageHelper.startPage(pageSupport.getPageNum(), pageSupport.getPageSize());
        } else {
            limitTo();
        }
        if (StringUtils.isNotEmpty(pageSupport.getOrderByColumn())
                && StringUtils.isNotEmpty(pageSupport.getIsAsc())) {
            PageHelper.orderBy(pageSupport.getOrderByColumn() + " " + pageSupport.getIsAsc());
        } else {
            order();
        }
    }
    /**
     * 表单提交参数
     * @param
     */
    public static void startPage() {
        limitTo();
        order();
    }

    private static void order() {
        String orderBy = ServletUtils.getParameter(ORDER_BY_COLUMN);
        String sort = ServletUtils.getParameter(SORT);
        if (StringUtils.isNotEmpty(orderBy)
                && StringUtils.isNotEmpty(sort)) {
            PageHelper.orderBy(orderBy + " " + sort);
        }
    }

    private static void limitTo() {
        Integer pageNum = ServletUtils.getParameterToInt(PAGE_NUM);
        Integer pageSize = ServletUtils.getParameterToInt(PAGE_SIZE);
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        } else {
            PageHelper.startPage(1, 10);
        }
    }
}
